package com.yimixian.app.util;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;

import com.ta.utdid2.android.utils.StringUtils;
import com.yimixian.app.AppService;
import com.yimixian.app.YMXApplication;
import com.yimixian.app.activity.BaseNaviFragmentGroupActivity;
import com.yimixian.app.common.Constants;
import com.yimixian.app.model.GoodsItem;

import java.util.ArrayList;
import java.util.List;

import retrofit.client.Header;
import retrofit.client.Response;

/**
 * service的工具类
 * Created by zhilian-2 on 2016/1/20.
 */
public class ServiceUtils {

    private final static String TAG = "ServiceUtils";
    private final static String DATE = "Date";
    /**
     * 获取appservice实例接口
     */
    public interface GetAppServiceListener{
        void getService(AppService appService);
    }

    /**
     * service运行期间的刷新数据 解绑服务接口
     */
    public interface CountDownDataListener{
        void isNeedUpdate();
        void isNeedUnbindService();
    }

    /**
     * 绑定Service
     * @param context
     * @param conn
     * @param receiver
     * @param listener
     */
    public static ServiceConnection bindAndGetService(final Context context,ServiceConnection conn,
                                         final BroadcastReceiver receiver,
                                         final GetAppServiceListener listener){
        if (!isAppServiceWorked()) YMXApplication.getInstance().startAppService();
        if (context == null) return null;
        if (conn == null)
            conn = new ServiceConnection() {
            @Override
            public void onServiceDisconnected(ComponentName name) {
            }
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                AppService mAppService = ((AppService.MsgBinder)service).getService();
                if (listener != null && mAppService != null) {
                    if (receiver != null) registerBroadcastReceiver(context, receiver);
                    listener.getService(mAppService);
                }
            }
        };
        Intent intent = new Intent(context, AppService.class);
        context.bindService(intent, conn, Context.BIND_AUTO_CREATE);
        return conn;
    }

    public static void unbindService(Context context, ServiceConnection conn){
        if (conn != null) {
            try {
                context.unbindService(conn);
            }catch (Exception e){
                Log.e(TAG, e.getMessage());
            }
        }
    }
    /**
     * 注册广播
     */
    public static void registerBroadcastReceiver(Context context, BroadcastReceiver receiver){
        if (context == null || receiver == null) return;
        IntentFilter filter = new IntentFilter(Constants.ServicePageType.HOMEFRAGMENT);
        filter.addAction(Constants.ServicePageType.TOUNBINDSERVICE);
        filter.addAction(Constants.ServicePageType.SESSIONFRAGMENT);
        filter.addAction(Constants.ServicePageType.SEARCHFRAGMENT);
        filter.addAction(Constants.ServicePageType.CATEGORYFRAGMENT);
        context.registerReceiver(receiver, filter);
    }

    /**
     * 解绑广播
     */
    public static void unregisterReceiver(Context context, BroadcastReceiver receiver){
        if (receiver != null && context != null) {
         try {
             context.unregisterReceiver(receiver);
         }catch (Exception e){
             e.printStackTrace();
          }
        }
    }

    /**
     * 判断是否需要绑定service及所需数据 及筛选粗remaining_time>0
     * @param context
     * @param mList
     * @param pageType  页面名称
     */
    public static void infilterServiceData(Context context, List<GoodsItem> mList, String pageType){
        if (context == null) return;
        if (mList != null && mList.size() > 0) {
            setData(context, mList, pageType);
        }

    }

    public static void setData(Context context,List<GoodsItem> mList, String pageType){
        List<GoodsItem> list = new ArrayList<>();
        for (GoodsItem goodsItem : mList){
            goodsItem.remaining_time = goodsItem.start_time - YMXApplication.getInstance().responseTime;
            if (goodsItem != null && goodsItem.remaining_time > 0){
                list.add(goodsItem);
            }
        }
        ((BaseNaviFragmentGroupActivity)context).initCountDownData(list, pageType);
    }
    /**
     * 本方法判断自己些的一个Service 是否已经运行
     * @return
     */
    public static boolean isAppServiceWorked() {
        int maxNum = 40;
        ActivityManager myManager=(ActivityManager)YMXApplication.getInstance().
                getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningService =
                (ArrayList<ActivityManager.RunningServiceInfo>) myManager.getRunningServices(maxNum);
        for(int i = 0 ; i<runningService.size();i++) {
            if(runningService.get(i).service.getClassName().toString().
                    equals("com.yimixian.app.AppService")) {
                return true;
            }
        }
        return false;
    }

    public static void setTime(Response response){
        if (response == null) return;
        List<Header> list = response.getHeaders();
        if (list != null && list.size() > 0){
            for (Header header : list){
                String name = header.getName();
                if (!StringUtils.isEmpty(name) && name.equals(ServiceUtils.DATE) &&
                        !StringUtils.isEmpty(header.getValue())){
                    initApplacationTime(header.getValue());
                    break;
                }
            }
        }
    }

    public static void initApplacationTime(String timeString){
        long serviceTime = DateUtil.parseRfc1123DateTime(timeString).getTime();
        YMXApplication.getInstance().responseTime = serviceTime / 1000;
    }

}
